package com.zhao.leetcode.linked.medium;

import com.zhao.leetcode.linked.DeleteNNode;
import com.zhao.leetcode.linked.ListNode;

/**
 * @program: arithmetic-do-exercise
 * @author: zhaohuan
 * @create: 2025-10-11 17:18
 *
 * 地址：https://leetcode.cn/problems/swapping-nodes-in-a-linked-list/description/
 * 给你链表的头节点 head 和一个整数 k 。
 *
 * 交换 链表正数第 k 个节点和倒数第 k 个节点的值后，返回链表的头节点（链表 从 1 开始索引）。
 *
 * @description
 **/
public class ExchangeLinkedNode {


    public static void main(String[] args) {

        String s1 = "1234";
        String s2 = "1234";
        System.out.println(s1 == s2);

        ListNode head = new ListNode(1);
        ListNode two = new ListNode(2);
        ListNode three = new ListNode(3);
        ListNode four = new ListNode(4);
        ListNode five = new ListNode(5);
//        four.next = five;
        three.next = four;
        two.next = three;
        head.next = two;

        ExchangeLinkedNode node = new ExchangeLinkedNode();
        node.swapNodes(head, 2);

    }

    public ListNode swapNodes(ListNode head, int k) {
        if (head.next == null) {
            return head;
        }

        ListNode addHead = new ListNode(-1);
        addHead.next = head;

        ListNode exchangeLeft = addHead, exchangeRight = addHead, slow = head;

        while(k > 0) {
            if (k - 1 > 0) {
                exchangeLeft = exchangeLeft.next;
            }
            slow = slow.next;
            k--;
        }


        while (slow != null) {
            exchangeRight = exchangeRight.next;
            slow = slow.next;
        }

        if (exchangeRight == addHead) {
            int temp = exchangeRight.next.val;
            exchangeRight.next.val = exchangeLeft.next.val;
            exchangeLeft.next.val = temp;
            return addHead.next;
        }

        if (exchangeRight.next == null) {
            exchangeRight.next = exchangeLeft.next;
            exchangeLeft = exchangeLeft.next.next;
            exchangeRight.next.next = null;
            return addHead.next;
        }


        if (exchangeLeft.next  == exchangeRight) {

            int temp = exchangeRight.val;
            exchangeRight.val = exchangeRight.next.val;
            exchangeRight.next.val = temp;

        } else if (exchangeRight.next == exchangeLeft) {
            int temp = exchangeLeft.val;
            exchangeLeft.val = exchangeLeft.next.val;
            exchangeLeft.next.val = temp;

        } else if (exchangeLeft != exchangeRight) {
            ListNode left = exchangeRight.next;
            exchangeRight.next = exchangeRight.next.next;

            ListNode right = exchangeLeft.next;

            exchangeLeft.next = exchangeLeft.next.next;

            left.next = exchangeLeft.next;
            exchangeLeft.next = left;

            right.next = exchangeRight.next;
            exchangeRight.next = right;
        }


        return addHead.next;

    }

}
